<template>
  <upload-component></upload-component>
</template>

<script setup lang="tsx">
import { FormItem, RequestMethodResponse, Upload, UploadFile } from 'tdesign-vue-next';
import { inject, onMounted, Ref } from 'vue';

import { uploadFile } from '@/libs/utils/dataTreating';

import { TDFormItemType } from '../type.d';

const {
  componentAttribute = {},
  formItemAttribute = {},
  name,
} = defineProps<{
  componentAttribute: TDUploadType;
  name: string;
  formItemAttribute: TDFormItemType;
}>();

type TDUploadType = InstanceType<typeof Upload>['$props'];

const requestMethod = async (files: UploadFile | UploadFile[]): Promise<RequestMethodResponse> => {
  try {
    let rawNow;
    if (Array.isArray(files)) {
      const { raw } = files[files.length - 1];
      if (raw) {
        rawNow = raw;
      }
    } else {
      const { raw } = files;
      rawNow = raw;
    }

    const { url } = await uploadFile(rawNow);

    if (url) {
      return {
        status: 'success',
        response: { url },
      };
    }

    return {
      status: 'fail',
      response: { url: '' },
    };
  } catch (error) {
    console.error('图片上传失败：', error);
    return { status: 'fail', error: '上传失败', response: { url: '' } };
  }
};

const defaultComponentAttribute: TDUploadType = {
  placeholder: `请选择${formItemAttribute.label || ''}`,
  sizeLimit: { size: 20, unit: 'MB', message: '文件大小不超过 {sizeLimit} MB' },
  requestMethod,
  accept: componentAttribute?.theme === 'image' || componentAttribute?.theme === 'image-flow' ? 'image/*' : null,
};
const defaultFormItemAttribute: TDFormItemType = {
  name,
  rules: [
    {
      required: true,
      message: `${formItemAttribute.label || '此项'}必填`,
      trigger: 'change',
    },
  ],
};

const modelValue: Ref = inject('dynamicFormData');

const initData = () => {
  if (typeof modelValue?.value[name] === 'string') {
    if (modelValue.value[name].length === 0) {
      modelValue.value[name] = [];
    } else {
      modelValue.value[name] = JSON.parse(modelValue.value[name] || '[]');
    }
  }
};
initData();

onMounted(() => {
  initData();
});

const UploadComponent = (
  <FormItem {...defaultFormItemAttribute} {...formItemAttribute}>
    <Upload v-model={modelValue.value[name]} {...defaultComponentAttribute} {...componentAttribute} />
  </FormItem>
);
</script>

<style scoped></style>
